package com.shell.scheduler;

import com.shell.bee.base.bootstrap.Bootable;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.scheduler.job.po.SchdJob;
import com.shell.scheduler.job.service.ScheJobService;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

public class SchedulerBootstrap implements Bootable, InitializingBean {
	private final Log logger = LogFactory.getLog(getClass());
	@Autowired
	public ScheJobService scheJobService;

	public void afterPropertiesSet() throws Exception {
		startup();
	}

	public void startup() {
		this.logger.info("ScheduleBootstrap启动开始");

		Scheduler scheduler = getScheduler();
		if (scheduler == null) {
			try {
				throw new SchedulerException("Scheduler is null. ");
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
		}
		List<SchdJob> jobs = this.scheJobService.findEnabledJobs();

		SchedulerManager.scheduler = scheduler;
		SchedulerManager.addJobs(jobs);
		SchedulerManager.start();

		this.logger.info("ScheduleBootstrap启动结束.");
	}

	private Scheduler getScheduler() {
		Scheduler scheduler = null;
		try {
			scheduler = (StdScheduler) SpringContextUtil.getBean("schedulerFactoryBean");
		} catch (Exception e) {
			this.logger.warn(e.getMessage());
			try {
				scheduler = StdSchedulerFactory.getDefaultScheduler();
			} catch (SchedulerException e1) {
				e1.printStackTrace();
			}
		}
		return scheduler;
	}
}